package org.particles.gui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.LayoutManager;

import javax.swing.BorderFactory;
import javax.swing.JPanel;

import org.particles.common.CommonUtil;
import org.particles.domain.Particle;
import org.particles.domain.Vector2D;
import org.particles.domain.world.World;

public class WorldPanel extends JPanel {
	private static final long serialVersionUID = 8673205854997802778L;
	private World world;

	public World getWorld() {
		return world;
	}

	public void setWorld(World world) {
		this.world = world;
		final Vector2D coordinate = (Vector2D) world.getDimension();
		setPreferredSize(
			new Dimension(
				CommonUtil.roundToInt(coordinate.getX()),
				CommonUtil.roundToInt(coordinate.getY())
			)
		);
	}

	public WorldPanel() {
		super();
		initPanel();
	}

	public WorldPanel(boolean isDoubleBuffered) {
		super(isDoubleBuffered);
		initPanel();
	}

	public WorldPanel(LayoutManager layout, boolean isDoubleBuffered) {
		super(layout, isDoubleBuffered);
		initPanel();
	}

	public WorldPanel(LayoutManager layout) {
		super(layout);
		initPanel();
	}
	
	private void initPanel() {
		setBorder(BorderFactory.createLineBorder(Color.GREEN));
		setBackground(Color.BLACK);
	}

	public void paintComponent(Graphics g) {
		super.paintComponent(g);

		for(Particle particle : world.getParticles()) {
			if(particle instanceof GuiParticle) {
				g.setColor( ((GuiParticle) particle).getColor() );
			}
			else {
				g.setColor(Color.WHITE);
			}
			final Vector2D coordinate = (Vector2D) particle.getSpacePlace();
			final int diameter = CommonUtil.roundToInt(particle.getRadius() * 2);
			g.drawOval(
					CommonUtil.roundToInt(coordinate.getX()), 
					CommonUtil.roundToInt(coordinate.getY()), 
					diameter, diameter);
		}
	}
}
